package com.ldk.base.framework.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 敏感词过滤工具
 * 
 * @author xiangwl
 * 
 */
public class SensitiveWordUtil {

	private static final Logger logger = LoggerFactory
			.getLogger(SensitiveWordUtil.class);
	public static final String BAD_WORDS_LIB_FILE_NAME = "words/sensitive_words.txt";

	// 脏字库
	private static Set<Character> sensitiveCharSet = null;
	// 敏感词库
	private static Set<String> sensitiveWordSet = null;

	/**
	 * 敏感词过滤
	 * 
	 * @param content
	 *            内容
	 * @param replaceString
	 *            敏感词替换字符串,默认为****
	 * @return
	 */
	public static String filterSensitive(String content, String replaceString) {
		if (StringUtils.isEmpty(replaceString)) {
			replaceString = "*";
		}
		String newContent = content;
		try {
			List<String> sensitiveList = checkSensitiveWord(content);
			if (sensitiveList != null && !sensitiveList.isEmpty()) {
				for (String sensitive : sensitiveList) {
					if(StringUtils.isEmpty(sensitive)) continue;
					String replace="";
					int len = sensitive.length();
					for (int i = 0; i < len; i++) {
						replace += replaceString;
					}
					newContent = newContent.replace(sensitive, replace);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}

		return newContent;
	}

	/**
	 * 初始化敏感词库
	 */
	private static void init() {
		// 初始化容器
		sensitiveCharSet = new HashSet<>();
		sensitiveWordSet = new HashSet<>();
		// 读取文件 创建敏感词库
		readSensitiveWords();
	}

	/**
	 * 读取本地的敏感词文件
	 * 
	 * @return
	 */
	private static void readSensitiveWords() {
		try {
			// 敏感词词库所在目录，这里为txt文本，一个敏感词一行
			String filePath = SensitiveWordUtil.class.getResource("classpath*:words/sensitive_words.txt").getFile();
			File file = new File(filePath);

			List<String> words = FileUtils.readLines(file, "UTF-8");
			for (String line : words) {
				String word = line.trim();
				sensitiveWordSet.add(word);
				for (Character c : word.toCharArray()) {
					sensitiveCharSet.add(c);
				}
			}
		} catch (UnsupportedEncodingException e) {
			logger.error("敏感词库文件转码失败!");
		} catch (FileNotFoundException e) {
			logger.error("敏感词库文件不存在!");
		} catch (IOException e) {
			logger.error("敏感词库文件读取失败!");
		}
	}

	/**
	 * 检查敏感词
	 * 
	 * @return
	 */
	private static List<String> checkSensitiveWord(String text) {
		if (sensitiveWordSet == null || sensitiveCharSet == null) {
			init();
		}
		List<String> sensitiveWords = new ArrayList<>();
		for (int i = 0; i < text.length(); i++) {
			Character word = text.charAt(i);
			if (!sensitiveCharSet.contains(word)) {
				continue;
			}
			int j = i;
			while (j < text.length()) {
				if (!sensitiveCharSet.contains(word)) {
					break;
				}
				String key = text.substring(i, j + 1);
				if (sensitiveWordSet.contains(key)) {
					sensitiveWords.add(key);
				}
				j++;
			}
		}
		return sensitiveWords;
	}
}
